package com.xipu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xipu.yygh.cmn.listener.DictListener;
import com.xipu.yygh.cmn.mapper.DictMapper;
import com.xipu.yygh.cmn.service.DictService;
import com.xipu.yygh.common.exception.YyghException;
import com.xipu.yygh.model.cmn.Dict;
import com.xipu.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * description: 数据字典Service
 * @author: gql
 * @date: 2022/04
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict>
        implements DictService {
    /**
     * 数据字典上传监听器
     */
    @Autowired
    private DictListener dictListener;

    /**
     * 数据字典表
     */
    @Autowired
    private DictMapper dictMapper;

    /**
     * 导入Excel
     * 注意：形参必须是file,这是element-ui底层封装提供的变量名
     * @param file 文件上传对象
     * @return 是否导入成功
     */
    @Override
    public void importDictData(MultipartFile file) {
        try {
            // read(args1,args2,args3):输入流、实体类class、监听器
            EasyExcel.read(file.getInputStream(), DictEeVo.class, dictListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getNameByDictCodeAndValue(String parentDictCode, String value) {
        if (StringUtils.isEmpty(parentDictCode)) {
            // 如果parentDictCode为空，则根据value也能唯一定位数据字典
            LambdaQueryWrapper<Dict> eq = Wrappers.lambdaQuery(Dict.class).eq(Dict::getValue, value);
            Dict dict = this.baseMapper.selectOne(eq);
            if (StringUtils.isEmpty(dict)) {
                throw new YyghException(20001, "数据不存在");
            } else {
                return dict.getName();
            }
        } else {
            // 否则需要dictCode
            Dict dict = this.dictMapper.getNameByDictCodeAndValue(parentDictCode, value);
            if (StringUtils.isEmpty(dict)) {
                throw new YyghException(20001, "数据不存在");
            } else {
                return dict.getName();
            }
        }
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        List<Dict> dictList = this.dictMapper.findByDictCode(dictCode);
        if (StringUtils.isEmpty(dictList)) {
            throw new YyghException(20001, "数据不存在");
        } else {
            return dictList;
        }
    }

    /**
     * 导出方法
     * @param response http响应
     */
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            // 1.设置下载头和其他信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // URLEncoder.encode可以防止中文乱码
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 2.把数据字典表所有数据查询出来 List<Dict>  --->  List<DictEeVo>
            List<Dict> dictList = this.list();
            List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
            for (Dict dict : dictList) {
                DictEeVo dictVo = new DictEeVo();
                BeanUtils.copyProperties(dict, dictVo);
                dictVoList.add(dictVo);
            }

            // 3.写出到Excel中
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("数据字典")
                    .doWrite(dictVoList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 数据字典懒加载
     * @param id 要查询的id
     * @return id下一层数据列表
     */
    @Cacheable(value = "dict")
    @Override
    public List<Dict> findChildData(Long id) {
        LambdaQueryWrapper<Dict> eq = Wrappers.lambdaQuery(Dict.class).eq(Dict::getParentId, id);
        List<Dict> dictList = this.list(eq);
        for (Dict dict : dictList) {
            dict.setHasChildren(this.hasChild(dict.getId()));
        }
        return dictList;
    }

    /**
     * 是否拥有子结点
     * @param id id
     * @return 是否有子结点
     */
    private boolean hasChild(Long id) {
        LambdaQueryWrapper<Dict> eq = Wrappers.lambdaQuery(Dict.class).eq(Dict::getParentId, id);
        return this.baseMapper.selectCount(eq) > 0;
    }
}
